package com.sgb.kjwl.view.ui.fragment.transport;

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sgb.capital.model.PayInfoEntity;
import com.sgb.capital.view.ui.activity.BusinessManagementActivity;
import com.sgb.capital.view.ui.activity.PersonPayActivity;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentTransportOrderOwnerBinding;
import com.sgb.kjwl.di.transport.DaggerTransportFragComponent;
import com.sgb.kjwl.di.transport.TransportFragModule;
import com.sgb.kjwl.model.entity.transport.order.MyOrderEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.transport.TransportOrderOwnerAdapter;
import com.sgb.kjwl.viewmodel.transport.TransportOrderOwnerViewModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * Time:2021/2/3
 * Author:黄淋
 * Description:货主运输订单
 */
public class TransportOrderOwnerFragment extends AppLazyFragment implements TransportOrderOwnerAdapter.OrderOnClickListener {
    @Inject
    TransportOrderOwnerViewModel viewModel;

    private FragmentTransportOrderOwnerBinding mBinding;
    private TransportOrderOwnerAdapter mAdapter;
    private static final int REQUEST_CODE_REFRESH = 4;
    public static final int TO_GOODS_ORDER = 100;//跳转订单详情
    Map mMap;
    private int tabposition = 0;
    private MyOrderEntity entity;

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTransportFragComponent.builder().appComponent(appComponent)
                .transportFragModule(new TransportFragModule(this))
                .build()
                .inject(this);
    }

    public static TransportOrderOwnerFragment newInstance(int position) {
        TransportOrderOwnerFragment fragment = new TransportOrderOwnerFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(RouterKey.TYPE, position);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_transport_order_owner, container, false);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        mMap = new HashMap();
        tabposition = getArguments().getInt(RouterKey.TYPE);
        mAdapter = new TransportOrderOwnerAdapter(getContext(), null);
        mAdapter.SetOrderListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mBinding.recyclerView.setLayoutManager(layoutManager);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        mBinding.recyclerView.setAdapter(mAdapter);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getList(getContext(), false, mMap);
            }

            @Override
            public void onLoadMore() {
                viewModel.getList(getContext(), true, mMap);
            }
        });

        mAdapter.setOnItemClick(new AdapterOnItemClick<MyOrderEntity>() {
            @Override
            public void onItemClick(MyOrderEntity MyOrderEntity, int position) {
                ActivityJump.jumpToActivity(getContext(), TransportOrderDetailOwnerActivity.class, Pair.create("no", MyOrderEntity.getOrderNo()),
                        Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.GOODS_OWNER));
            }
        });
        viewModel.ldTradeNo.observe(getActivity(), tradeNo -> {
            if (UserOperating.getInstance().isCompany()) {//企业
                //                订单列表和订单详情企业支付运费跳待付订单
                BusinessManagementActivity.start(getContext(), 1);
            } else {//团队 进资金中心
                if ("".equals(tradeNo) || entity == null) {
                    return;
                }
                PayInfoEntity paymentEntity = new PayInfoEntity();
                paymentEntity.amount = Double.valueOf(entity.getAllFreight());
                paymentEntity.tradeNo = tradeNo.getTradeNo();
                paymentEntity.orderId = tradeNo.getFreightOrderNo();
                PersonPayActivity.start(getActivity(),  tradeNo.getFreightOrderNo());
            }
        });
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onLazyLoad() {
        if (UserOperating.getInstance().isCompany()) {
            mMap.put("companyNo", UserOperating.getInstance().getTeamOrCompanyNameNo());
        } else if (UserOperating.getInstance().isPersonal()) {
            mMap.put("terminal", 3);
        } else {
            mMap.put("teamNo", UserOperating.getInstance().getTeamOrCompanyNameNo());
        }
        viewModel.getList(getContext(), false, mMap);
    }


    /**
     * 显示数据
     *
     * @param list       数据
     * @param isLoadMore 是否加载更多
     */
    public void showList(List<MyOrderEntity> list, boolean isLoadMore) {
        mBinding.recyclerView.refreshComplete();
        if (isLoadMore) {
            if (null != list && list.size() > 0) {
                mBinding.recyclerView.loadMoreComplete();
                mAdapter.addDatas(list);
            } else {
                mBinding.recyclerView.setNoMore(true);
            }
            mBinding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            mBinding.recyclerView.refreshComplete();
            if (null != list && list.size() > 0) {
                mBinding.recyclerView.setVisibility(View.VISIBLE);
                mBinding.emptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
                mBinding.recyclerView.setLoadingMoreEnabled(true);
                mAdapter.notifyDataSetChanged();
            } else {
                mAdapter.setDatas(null);
                mBinding.recyclerView.setVisibility(View.GONE);
                mBinding.emptyView.setVisibility(View.VISIBLE);
                mBinding.recyclerView.setLoadingMoreEnabled(true);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_TRANSPORT_ORDER_LIST) {
            refreshData(tabposition);
        }
    }

    @Override
    public void btnGoClick(String s, MyOrderEntity item) {
        this.entity = item;
        switch (s) {
            case "确认订单":
                OrderDialog("您确定由" + item.getCarNumber() + "的车主" + item.getUserName() + "运输货物吗？", 1, item);
                break;
            case "支付运费":
                OrderDialog("由 " + item.getCityName() + " " + item.getDistrictName() + " " + "→" + " " + item.getDestCityName() + " " + item.getDestDistrictName() + "的待支付运费为" + item.getAllFreight() + "元，您确定要支付该笔运费吗？", 2, item);
                break;
        }
    }

    //彈窗
    private void OrderDialog(String content, int type, MyOrderEntity item) {
        new RoundDialog.Builder(getContext())
                .title("提示")
                .content(content)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(v -> {
                    if (type == 2) {
                        if (item != null) {
                            viewModel.getPayFreight(getContext(), item.getOrderNo());
                        }
                    } else if (type == 1) {
                        viewModel.getSureOrder(getContext(), item);
                    }
                })
                .show();
    }

    public void refreshData(int tabPosition) {
        if (tabPosition != 0) {
            if (tabPosition == 4) {
                mMap.put("status", 6);
            } else if (tabPosition == 5) {
                mMap.put("status", 4);
            } else {
                mMap.put("status", tabPosition);
            }
        }
        if (UserOperating.getInstance().isCompany()) {
            mMap.put("companyNo", UserOperating.getInstance().getTeamOrCompanyNameNo());
        } else if (UserOperating.getInstance().isPersonal()) {
            mMap.put("terminal", 3);
        } else {
            mMap.put("teamNo", UserOperating.getInstance().getTeamOrCompanyNameNo());
        }
        viewModel.getList(getContext(), false, mMap);
    }

    /**
     * 确认订单成功
     */
    public void sureOrderSuccess(MyOrderEntity item) {
        MToast.showToast(getContext(), "操作成功");
        EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.SHIPPING_ORDER_SUCCESSFUL));
        ActivityJump.jumpToActivity(getContext(), TransportOrderDetailOwnerActivity.class, Pair.create("no", item.getOrderNo()),
                Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.GOODS_OWNER));
    }
}
